package com.kucai.yifaqapp.util;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.view.Gravity;
import android.widget.Toast;

import com.google.gson.Gson;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class MyUtils {
    private static final ThreadLocal<SimpleDateFormat> simpleDateFormatYear = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy", Locale.CHINA);
        }
    };

    private static final ThreadLocal<SimpleDateFormat> simpleDateFormat1 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("MM-dd", Locale.CHINA);
        }
    };

    public static final ThreadLocal<SimpleDateFormat> simpleDateFormat3 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        }
    };
    public static final ThreadLocal<SimpleDateFormat> simpleDateFormat4 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        }
    };
    private static final ThreadLocal<SimpleDateFormat> simpleDateFormat5 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("HH:mm", Locale.CHINA);
        }
    };
    private static final ThreadLocal<SimpleDateFormat> simpleDateFormatMDHM = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("MM月dd日 HH:mm", Locale.CHINA);
        }
    };


    public static String getTime() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        String str = String.valueOf(time);
        return str;
    }

//    private static final SimpleDateFormat simpleDateFormatYear = new SimpleDateFormat("yyyy", Locale.CHINA);
//    private static final SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("MM-dd", Locale.CHINA);
//    private static final SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy", Locale.CHINA);
//    public static final SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
//    public static final SimpleDateFormat simpleDateFormat4 = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
//    private static final SimpleDateFormat simpleDateFormat5 = new SimpleDateFormat("HH:mm", Locale.CHINA);
//    private static final SimpleDateFormat simpleDateFormatMDHM = new SimpleDateFormat("MM月dd日 HH:mm", Locale.CHINA);

    private static DecimalFormat decimalFormat = new DecimalFormat("###,###,###,##0.00");
//    private static Gson gson = new Gson();


    /**
     * 检查当前网络是否可用
     *
     * @return
     */

    public static boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    /**
     * 正则表达式:验证身份证
     */
    public static final String REGEX_ID_CARD = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)";

    /**
     * 校验身份证
     *
     * @param idCard
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isIDCard(String idCard) {
        return Pattern.matches(REGEX_ID_CARD, idCard);
    }


    /**
     * 带两位小数点的默认为元的显示
     *
     * @param amount 金额
     * @return String 金额字符串
     */
    public static String FormatAmountStr2(long amount) {
        double d_amount = (double) amount / 100;
        return decimalFormat.format(d_amount);
    }

    /**
     * 后罪名加万元，专用于列表显示
     *
     * @param amount 金额
     * @return 金额字符串
     */
    //格式化金额
    public static String FormatAmountStr(long amount) {

        Double _amount = (double) amount;
        _amount = _amount / 100;
        if (_amount < 10000)
            return String.format(Locale.CHINA, "%.00f元", _amount);

        int tail = (int) (_amount % 10000.00);
        if (tail == 0)
            return String.format(Locale.CHINA, "%.0f万", _amount / 10000);

        tail = (int) (_amount % 1000.00);
        if (tail == 0)
            return String.format(Locale.CHINA, "%.1f万", _amount / 10000);

        tail = (int) (_amount % 100.00);
        if (tail == 0)
            return String.format(Locale.CHINA, "%.2f万", _amount / 10000);

        tail = (int) (_amount % 10.00);
        if (tail == 0)
            return String.format(Locale.CHINA, "%.3f万", _amount / 10000);

        return String.format(Locale.CHINA, "%.4f万", _amount / 10000);
    }

    //格式化利率
    public static String FormatRateStr(int rate) {
        double _rate = (double) rate;
        int tail = (int) (_rate % 100.00);
        if (tail == 0)
            return String.format(Locale.CHINA, "%.0f%s", _rate / 100, "%");

        tail = (int) (_rate % 10.00);
        if (tail == 0)
            return String.format(Locale.CHINA, "%.1f%s", _rate / 100, "%");

        return String.format(Locale.CHINA, "%.2f%s", _rate / 100, "%");
    }

    //格式化利率
    public static String FormatRateStr2(int rate) {
        double _rate = (double) rate;
        int tail = (int) (_rate % 100.00);
        if (tail == 0)
            return String.format(Locale.CHINA, "%.0f", _rate / 100);

        tail = (int) (_rate % 10.00);
        if (tail == 0)
            return String.format(Locale.CHINA, "%.1f", _rate / 100);

        return String.format(Locale.CHINA, "%.2f", _rate / 100);
    }

    public static String FormatRateStr3(int rate) {
        double _rate = (double) rate;
        return String.format(Locale.CHINA, "%.2f%s", _rate / 100, "%");
    }


    public static String FormatRateStr4(int rate) {
        double _rate = (double) rate;
        return String.format(Locale.CHINA, "%.2f%s", _rate / 12, "");
    }


    /**
     * 显示toast 无论主线程，还是子线程
     */
    private static void showToast(final Activity ctx, final String msg) {
        if (null == ctx)
            return;

        if ("main".equals(Thread.currentThread().getName())) {
            Toast toast = Toast.makeText(ctx, msg, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        } else {
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast toast = Toast.makeText(ctx, msg, Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
            });
        }
    }


    /**
     * 手机号效验
     */
    private static boolean checkMobile(String mobile) {
        Pattern p = Pattern.compile("^((13)|(14)|(15)|(16)|(17)|(18))\\d{9}$");
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /**
     * 手机号输入效验
     */
    public static boolean checkMobile(Activity act, String mobile) {
        if (TextUtils.isEmpty(mobile)) {
            MyUtils.showToast(act, "请输入手机号");
            return false;
        } else if (mobile.length() != 11) {
            MyUtils.showToast(act, "手机号格式输入有误,请重新输入");
            return false;
        }
        return true;
    }

    /**
     * 邮箱校验
     */
    public static boolean checkEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public static boolean checkEmail(Activity act, String email) {
        if (TextUtils.isEmpty(email)) {
            MyUtils.showToast(act, "请输入邮箱");
            return false;
        } else if (!MyUtils.checkEmail(email)) {
            MyUtils.showToast(act, "邮箱格输入有误,请重新输入");
            return false;
        }
        return true;
    }

    /**
     * 登录密码校验
     */
    private static boolean checkPassword(String password) {
        String str = "^([0-9A-Za-z]{6,20})$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(password);
        return m.matches();
    }

    /**
     * 登录密码校验
     */
    public static boolean checkPassword(Activity act, String password) {

        if (TextUtils.isEmpty(password)) {
            MyUtils.showToast(act, "请输入密码");
            return false;
        } else if (!MyUtils.checkPassword(password)) {
            MyUtils.showToast(act, "请输入有效密码");
            return false;
        }
        return true;
    }

    /**
     * 手机6位验证码校验
     */
    public static boolean checkMCode(String code) {
        String str = "^([0-9]{6})$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(code);
        return m.matches();
    }

    public static boolean checkMCode(Activity act, String code) {
        if (TextUtils.isEmpty(code)) {
            MyUtils.showToast(act, "请输入验证码");
            return false;
        }
        if (!checkMCode(code)) {
            MyUtils.showToast(act, "验证码格式错误");
            return false;
        }
        return true;
    }

    /**
     * 手机6位邮箱验证码校验
     */
    public static boolean checkEmailCode(String code) {
        String str = "^([0-9A-Za-z]{6})$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(code);
        return m.matches();
    }

    public static boolean checkEmailCode(Activity act, String code) {
        if (TextUtils.isEmpty(code)) {
            MyUtils.showToast(act, "请输入验证码");
            return false;
        }
        if (!checkEmailCode(code)) {
            MyUtils.showToast(act, "验证码格式错误");
            return false;
        }
        return true;
    }

    /**
     * 绑定银行卡6位验证码校验
     */
    private static boolean checkBankCode(String code) {
        String str = "^([0-9]{6})$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(code);
        return m.matches();
    }

    public static boolean checkBankCode(Activity act, String code) {
        if (TextUtils.isEmpty(code)) {
            MyUtils.showToast(act, "请输入验证码");
            return false;
        }
        if (!checkBankCode(code)) {
            MyUtils.showToast(act, "验证码格式错误");
            return false;
        }
        return true;
    }


    /**
     * 姓名校验
     */
    public static boolean checkName(Activity act, String name) {
        if (TextUtils.isEmpty(name)) {
            MyUtils.showToast(act, "请输入姓名");
            return false;
        }
        return true;
    }

    /**
     * 身份证校验
     */
    public static boolean checkIdcard(Activity act, String idcard) {
        if (TextUtils.isEmpty(idcard)) {
            MyUtils.showToast(act, "请输入身份证号");
            return false;
        }
        return true;
    }

    /**
     * 银行卡校验
     */
    public static boolean checkbankcard(String card) {
        String str = "^([0-9]{14,19})$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(card);
        return m.matches();
    }

    /**
     * 校验银行卡卡号
     *
     * @param cardId
     * @return
     */
    public static boolean checkBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId
                .substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
     *
     * @param nonCheckCodeCardId
     * @return
     */
    public static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null
                || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            // 如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    /**
     * 身份证校验
     */
    public static boolean checkbankcard(Activity act, String bankcard) {
        if (TextUtils.isEmpty(bankcard)) {
            MyUtils.showToast(act, "请输入银行卡号");
            return false;
        }
        if (!checkbankcard(bankcard)) {
            MyUtils.showToast(act, "银行卡号格式错误,请检查");
            return false;
        }

        return true;
    }

    public static String simpleDateStringYear(Date date) {
        if (null == date)
            return "";
        return simpleDateFormatYear.get().format(date);
    }

    public static String simpleDateStringMd(Date date) {
        if (null == date)
            return "";
        return simpleDateFormat1.get().format(date);
    }

    public static String simpleDateStringMd(String date) {
        if (TextUtils.isEmpty(date))
            return "";
        return simpleDateFormat1.get().format(strToDate(date));
    }

    public static String simpleDateStringMDHM(Date date) {
        if (null == date)
            return "";
        return simpleDateFormatMDHM.get().format(date);
    }

    public static String simpleDateStringMDHM(String date) {
        if (TextUtils.isEmpty(date))
            return "";
        return simpleDateFormatMDHM.get().format(strToDate(date));
    }


    public static String simpleDateStringYMDHMS(Date date) {
        if (null == date)
            return "";
        return simpleDateFormat3.get().format(date);
    }

    public static String simpleDateStringYMDHMS(String date) {
        if (TextUtils.isEmpty(date))
            return "";
        return simpleDateFormat3.get().format(strToDate(date));
    }


    public static String simpleDateStringYMD(Date date) {
        if (null == date)
            return "";
        return simpleDateFormat4.get().format(date);
    }

    public static String simpleDateStringYMD(String date) {
        if (TextUtils.isEmpty(date))
            return "";
        return simpleDateFormat4.get().format(strToDate(date));
    }

    public static String simpleDateStringHm(Date date) {
        if (null == date)
            return "";
        return simpleDateFormat5.get().format(date);
    }

    public static List<Date> getSevendate(Date date) {

        List<Date> dates = new ArrayList<>();
        long oneDay = 24 * 60 * 60 * 1000;
        for (int i = 0; i < 7; i++) {
            Date newDate = new Date(date.getTime() + oneDay * i);
            dates.add(newDate);
        }
        return dates;
    }


    /**
     * 字符串转换成日期
     *
     * @param str 日期字符串
     * @return date
     */
    public static Date strToDate(String str) {
        if (str == null)
            return null;
        Date date = null;
        try {
            date = simpleDateFormat3.get().parse(str);
        } catch (ParseException e) {
            try {
                date = simpleDateFormat4.get().parse(str);
                return date;
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return date;
    }


    public static int daysOfTwo(Date fDate, Date oDate) {
        if (null == fDate || null == oDate)
            return 0;

        return (int) Math.ceil((double) (oDate.getTime() - fDate.getTime()) / 1000 / 60 / 60 / 24);
    }

    //持有天数
    public static int haveDays(Date loaninfoSdate, Date loanDetailDate) {
        long ldate = 0;
        long detailDate = 0;
        if (null != loaninfoSdate)
            ldate = loanDetailDate.getTime();

        if (null != loanDetailDate)
            detailDate = loanDetailDate.getTime();

        long tmp = ldate > detailDate ? ldate : detailDate;

        return (int) (new Date().getTime() - tmp) / 1000 / 60 / 60 / 24;
    }


    public static String returnLoanStatusNameWithStatus(int loanstatus) {
        String str = null;
        switch (loanstatus) {
            case 90:
                str = "募集中";
                break;
            case 150:
                str = "还款中";
                break;
            case 151:
            case 153:   //str = "代偿"; 客户端不允许出现代偿
            case 180:   //str = "项目归档";
                str = "还款完成";
                break;
            case 152:
                str = "逾期";
                break;
            case 160:
                str = "项目终止";
                break;
            case 170:
                str = "流标";
                break;
            default:
                break;
        }

        if (loanstatus > 90 && loanstatus < 150) {
            str = "已计息";
        }
        return str;
    }

    public static String returnDebtStatusNameWithStatus(int debtstatus, int loanstatus) {
        String str;
        if (debtstatus == 380) {
            str = "募集中";
        } else if (debtstatus == 390 && loanstatus == 150) {
            str = "还款中";
        } else {
            str = returnLoanStatusNameWithStatus(loanstatus);
        }
        return str;
    }

    /**
     * @param str        原始字符串
     * @param beginIndex 开始打码的位置
     * @param endIndex   结束打码的相对位置，只能是负数
     * @param maskCount  掩码长度
     * @return String 打码后的字符串
     */
    public static String maskTransfer(String str, int beginIndex, int endIndex, int maskCount) {
        if (TextUtils.isEmpty(str))
            return "";

        if (endIndex <= 0)
            endIndex = str.length() + endIndex;
        else
            endIndex = 0;
        String masks = "";
        for (int i = 0; i < maskCount; i++)
            masks += "*";
        return str.substring(0, beginIndex) + masks + str.substring(endIndex, str.length());
    }



    public static String mcouponDateDiff(String stime, String etime) throws ParseException {
        SimpleDateFormat formart = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = formart.parse(stime);
        Date date2 = formart.parse(etime);
        long times = date1.getTime() - date2.getTime();//这样得到的差值是微秒级别
        String daytime = times / (1000 * 60 * 60 * 24) + ""; //换算成天数
        return daytime;
    }


    /**
     * @param stime 开始时间
     * @param etime 结束时间
     * @return
     */
    public static int getMonthNum(String stime, String etime) {
        // 拆分年月日
        String[] stimeTmp = stime.split("-");
        String[] etimeTmp = etime.split("-");
        //得到etime月数
        int etimeRes = Integer.parseInt(etimeTmp[0]) * 12 + Integer.parseInt(etimeTmp[1]);
        if (Integer.parseInt(stimeTmp[2]) > Integer.parseInt(etimeTmp[2])) {
            etimeRes = etimeRes - 1;
        }
        //得到stime月数
        int stimeRes = Integer.parseInt(stimeTmp[0]) * 12 + Integer.parseInt(stimeTmp[1]);
        int resultTime = Math.abs(etimeRes - stimeRes);

        return resultTime;
    }

    /**
     * 将集合转化成字符串
     *
     * @param list
     * @return
     */
    public static String listToString(List list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i)).append(",");
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }

    /**
     * 将集合转化成字符串
     *
     * @param list
     * @return
     */
    public static String listUnderlineToString(List list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i)).append("_");
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }

    /**
     * 将集合转化成字符串
     *
     * @param str
     * @return
     */
    public static List<String> StringToList(String[] str) {
        List<String> list = new ArrayList<>();
        if (str != null && str.length > 0) {
            for (int i = 0; i < str.length; i++) {
                list.add(str[i]);
            }
        }
        return list;
    }

    /**
     * 字符串截取(截取小数点前的数据)
     */
    public static String cutOutStr(String str) {
        String result = str.substring(0, str.indexOf("."));
        return result;
    }

    /**
     * 字符串截取(截取小数点前的数据)
     */
    public static String cutOutStrBlank(String str) {
        if (str.contains(" ")) {
            str = str.substring(0, str.indexOf(" "));
        }
        return str;
    }

    /**
     * 将集转换成json串
     */

    public static String getJsonData(List<Object> list) {
        Gson gson = new Gson();
        String jsonstring = gson.toJson(list);
        return jsonstring;
    }

    /**
     * 科学计数法格式化
     *
     * @param formatNum
     * @return
     */
    public static String numFormat(String formatNum) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        Double tqd = new Double(formatNum);
        return String.valueOf(nf.format(tqd));
    }

    public static String numFormat1(double d) {
        NumberFormat nf = NumberFormat.getInstance();
        // 是否以逗号隔开, 默认true以逗号隔开,如[123,456,789.128]
        nf.setGroupingUsed(false);
        // 结果未做任何处理
        return nf.format(d);
    }


    public static String baseUrl(String url, Map<String, Object> map) {
        if (map != null) {
            String baseurl = "?";
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                baseurl += entry.getKey() + "=" + entry.getValue() + "&";
            }
            baseurl = baseurl.substring(0, baseurl.length() - 1);
            return url + baseurl;
        }
        return url;
    }

    /**
     * 得到当年当月的最大日期
     **/
    public static int MaxDayFromDay_OF_MONTH(int year, int month) {
        Calendar time = Calendar.getInstance();
        time.clear();
        time.set(Calendar.YEAR, year);
        time.set(Calendar.MONTH, month - 1);//注意,Calendar对象默认一月为0
        int day = time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数
        return day;
    }
}
